package cn.iocoder.yudao.module.ym.job;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.web.config.WebProperties;
import cn.iocoder.yudao.module.infra.dal.dataobject.config.ConfigDO;
import cn.iocoder.yudao.module.infra.dal.mysql.config.ConfigMapper;
import cn.iocoder.yudao.module.infra.enums.DictDataConstants;
import cn.iocoder.yudao.module.infra.enums.TicketLogRecordConstants;
import cn.iocoder.yudao.module.infra.enums.TicketStatusEnum;
import cn.iocoder.yudao.module.infra.enums.YmMessageEnum;
import cn.iocoder.yudao.module.system.api.notify.NotifyMessageSendApiImpl;
import cn.iocoder.yudao.module.system.api.notify.dto.NotifySendSingleToUserReqDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.dal.mysql.dict.DictDataMapper;
import cn.iocoder.yudao.module.ym.controller.admin.ticketlog.vo.TicketLogSaveReqVO;
import cn.iocoder.yudao.module.ym.dal.dataobject.site.SiteDO;
import cn.iocoder.yudao.module.ym.dal.dataobject.ticket.TicketDO;
import cn.iocoder.yudao.module.ym.dal.mysql.site.SiteMapper;
import cn.iocoder.yudao.module.ym.dal.mysql.ticket.TicketMapper;
import cn.iocoder.yudao.module.ym.service.ticketlog.TicketLogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.iocoder.yudao.module.infra.enums.DictTypeConstants.YM_WORD_TEMP_TYPE;

/**
 * 电站月巡检次数
 *
 * @author j-sentinel
 */
@Slf4j
@Component
public class InspectionCountJob implements JobHandler {


    @Resource
    private TicketMapper ticketMapper;

    @Resource
    private SiteMapper siteMapper;

    private final ExecutorService taskExecutor;

    @Autowired
    public InspectionCountJob(ExecutorService taskExecutor) {
        this.taskExecutor = taskExecutor;
    }


    @Override
    @TenantIgnore
    @Transactional
    public String execute(String param) {
        System.out.println("电站月巡检次数-------------------------------"+param);

        List<SiteDO> siteDOS = siteMapper.selectList();
        List<TicketDO> ticketDOS = ticketMapper.selectList(new LambdaQueryWrapperX<TicketDO>()
                .eq(TicketDO::getTicketStatus, TicketStatusEnum.COMPLETED.getCode())
                .apply("DATE_FORMAT(create_time,'%Y-%m')=  DATE_FORMAT(NOW(),'%Y-%m')"));

        Map<Long, Long> siteIdCounts = ticketDOS.stream()
                .map(TicketDO::getSiteId)
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        Collectors.counting()
                ));

        if (siteDOS == null || siteDOS.isEmpty()) {
            return "无电站数据需要更新";
        }

        ConcurrentLinkedQueue<SiteDO> updateList = new ConcurrentLinkedQueue<>();
        CountDownLatch latch = new CountDownLatch(siteDOS.size());

        for (SiteDO siteDO : siteDOS) {
            taskExecutor.execute(() -> {
                try {
                    Long siteId = siteDO.getId();
                    Long l = siteIdCounts.get(siteId);
                    if(l != null){
                        SiteDO copySite = new SiteDO();
                        copySite.setId(siteId);
                        copySite.setInspectionCount(l.intValue());
                        updateList.add(copySite);
                    }

                } catch (Exception e) {
                    log.error("处理电站 {} 失败: {}", siteDO.getId(), e.getMessage());
                } finally {
                    latch.countDown();
                }
            });
        }

        try {
            latch.await(); // 等待所有任务完成
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("等待线程任务中断: {}", e.getMessage());
        }

        if (!updateList.isEmpty()) {
            siteMapper.updateBatch(updateList, 1000); // 调整批量大小
        }


        return String.format("定时执行电站月巡检次数 %s 个",updateList.size());
    }

}
